package com.silverhaze.diamond.client.ui.filter;

import com.silverhaze.diamond.client.data.SpecificData;
import com.silverhaze.diamond.client.resources.ServiceResourceContainer;
import com.silverhaze.diamond.client.ui.UIStringConstants;
import com.silverhaze.diamond.client.ui.table.model.AbstractServiceTableModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * © Ivan Babanin (aka JavaBean) (21.07.2007 1:33:17)
 */
public class CustomersFilterPanel extends AbstractFilterPanel {
    private JTextField nameField;
    private JTextField phoneField;
    private JTextField addressField;

    public CustomersFilterPanel(AbstractServiceTableModel model, JToggleButton tBtn) {
        super(model, tBtn);

        init();
    }

    private void init() {
        nameField = createTextField(10);
        phoneField = createTextField(10);
        addressField = createTextField(10);

        JButton clearBtn = new JButton(ServiceResourceContainer.UNDO);
        clearBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                nameField.setText("*");
                phoneField.setText("*");
                addressField.setText("*");

                getModel().refreshModelAll();
            }
        });

        Box hBox = Box.createHorizontalBox();
        hBox.add(Box.createHorizontalStrut(6));
        hBox.add(new JLabel(UIStringConstants.NAME + ": "));
        hBox.add(Box.createHorizontalStrut(3));
        hBox.add(nameField);
        hBox.add(Box.createHorizontalStrut(6));
        hBox.add(new JLabel(UIStringConstants.PHONE + ": "));
        hBox.add(Box.createHorizontalStrut(3));
        hBox.add(phoneField);
        hBox.add(Box.createHorizontalStrut(6));
        hBox.add(new JLabel(UIStringConstants.ADDRESS + ": "));
        hBox.add(Box.createHorizontalStrut(3));
        hBox.add(addressField);
        hBox.add(Box.createHorizontalStrut(3));
        hBox.add(clearBtn);
        hBox.add(Box.createHorizontalStrut(6));

        Box vBox = Box.createVerticalBox();
        vBox.add(hBox);
        vBox.add(Box.createVerticalStrut(5));

        add(vBox, BorderLayout.CENTER);
    }

    private JTextField createTextField(int size) {
        JTextField field = new JTextField(size);
        field.setText("*");
        field.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent event) {
                applyData();
            }
        });
        return field;
    }

    public void applyData() {
        String name = nameField.getText().trim();
        String phone = phoneField.getText().trim();
        String address = addressField.getText().trim();

        getModel().fillData(SpecificData.filterCustomers(name, phone, address));
        getModel().refreshModel();
    }
}

